﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
using SevenZip;
using System.Threading;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TransferFiles" in code, svc and config file together.
public class TransferFiles : ITransferFiles
{
	private DAOFileTrans dao = new DAOFileTrans();
    static private string tempDir = @"c:\TempFiles"; //Default directory
    private string fileLocation;// String to strore full path to file
   // private string password; //Stores password for encryption
    private string storageDir = @"C:\storage\"; //Default Extracted directory
    //private string tempSplitDir = @"c:\TempTransFiles"; //Default directory


    //Thread Handlers

    static public List<Thread> threadStore = new List<Thread>();
    static public List<ManualResetEvent> threadActivity = new List<ManualResetEvent>();
    static public List<ManualResetEvent> threadTransfer = new List<ManualResetEvent>();
    static public List<FileStatus> fileContinuation = new List<FileStatus>();
   // private int contFile = -1;
    //private string downloadStatusString;
    //private int threadCont = 0;




    #region AuthUser
    public int AuthUser(string username, string pwd)
    {
        return dao.GetUserAuth(username, pwd);
    }
    #endregion


    #region DownloadFile
    public RemoteFileInfo DownloadFile(DownloadRequest request)
    {
        //int userAuth = dao.GetUserAuth(request.UserName, request.Password);

        HelperClass user = new HelperClass();

        user.UserName = request.UserName;
        user.PassHash = request.Password;

        

            //user.UserGroup = dao.getUsersGroup(user.UserName, user.PassHash);

            #region commented code
            //RemoteFileInfo result = new RemoteFileInfo();
            //try
            //{
            //    if (request.FilePart == "")
            //    {

            //        string filePath = System.IO.Path.Combine(@"c:\storage", request.FileName);
            //        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

            //        // check if exists
            //        if (!fileInfo.Exists)
            //            throw new System.IO.FileNotFoundException("File not found",
            //                                                        request.FileName);


            //        BeginSplitFiles(filePath, user, user.UserGroup);

            //        // open stream
            //        System.IO.FileStream stream = new System.IO.FileStream(filePath,
            //                    System.IO.FileMode.Open, System.IO.FileAccess.Read);

            //        // return result 
            //        result.FileName = request.FileName;
            //        result.FileSize = fileInfo.Length;

            //        result.FileByteStream = stream;
            //    }
            //    else
            //    {
            //        string fileName = Path.GetFileNameWithoutExtension(request.FileName);
            //        string fileExt = @".7z";
            //        string filePartName = fileName + request.FilePart + fileExt;
            //        string filePath = System.IO.Path.Combine(@"c:\HTCTemp\", filePartName);
            //        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

            //        // check if exists
            //        if (!fileInfo.Exists)
            //            throw new System.IO.FileNotFoundException("File not found",
            //                                                        filePartName);

            //        // open stream
            //        System.IO.FileStream stream = new System.IO.FileStream(filePath,
            //                    System.IO.FileMode.Open, System.IO.FileAccess.Read);

            //        // return result 
            //        result.FileName = request.FileName;
            //        result.FileSize = fileInfo.Length;

            //        result.FileByteStream = stream;

            //    }
            //}
            //catch (Exception ex)
            //{
            //    StreamWriter writer = new StreamWriter(@"C:\upload\temp\message.txt");
            //    writer.WriteLine(ex);
            //    writer.Close();

            //}
            //return result;
            #endregion

            if(request.FilePart.Contains(".password"))
            {
                BeginSplitFiles(request.FileName, user);
            }

            RemoteFileInfo result = new RemoteFileInfo();
            try
            {
                string activeDir = tempDir + "\\hct\\" + request.UserName + "\\" + Path.GetFileNameWithoutExtension(request.FileName) + "\\";
                string filePath = System.IO.Path.Combine(activeDir, request.FilePart);


                while (!File.Exists(filePath))
                {
                    //Thread.Sleep(10000);

                }

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
                // check if exists
                if (!fileInfo.Exists)
                    throw new System.IO.FileNotFoundException("File not found",
                                                              filePath);

                // open stream
                System.IO.FileStream stream = new System.IO.FileStream(filePath,
                      System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // return result 
                result.FileName = request.FileName;
                result.FileSize = fileInfo.Length;
                result.FileByteStream = stream;
            }
            catch (Exception ex)
            {
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\DownloadFileMessage.txt");
                writer.WriteLine(ex);

                writer.Close();
            }
            return result;
        
        
    }

    #endregion


    


    #region UploadFile
    public void UploadFile(RemoteFileInfo request)
    {
        try
        {
            //StreamWriter writer = new StreamWriter(@"C:\upload\temp\message3.txt");
            //writer.WriteLine(request.Password );

            //writer.Close();
            
            FileStream targetStream = null;
            Stream sourceStream = request.FileByteStream;

            string uploadFolder = tempDir + "\\" + request.Group + "\\" + Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(request.FileName)));

            Directory.CreateDirectory(uploadFolder);
            

            string filePath = Path.Combine(uploadFolder, Path.GetFileName(request.FileName));

            using (targetStream = new FileStream(filePath, FileMode.Create,
                                  FileAccess.Write, FileShare.None))
            {
                //read from the input stream in 65000 byte chunks

                const int bufferLen = 65000;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
                while ((count = sourceStream.Read(buffer, request.FileStart, bufferLen)) > 0)
                {
                    // save to output stream
                    targetStream.Write(buffer, request.FileStart, count);

                }
                targetStream.Close();
                sourceStream.Close();
                request.FileName = filePath;

                if(!Path.GetFileNameWithoutExtension(request.FileName).Contains(".password"))
                {
                    DecompressFiles(request);
                }

                


                
                if (Path.GetExtension(Path.GetFileNameWithoutExtension(request.FileName)).Contains("part" + request.NumParts.ToString("0000")))
                {
                    HelperClass hc = new HelperClass();
                    hc.UserName = request.UserName;
                    hc.PassHash = request.Password;
                   // request.FileName = extrPartsLoc;

                   // BeginSplitFiles(extrPartsLoc, hc, request.Group);
                    
                    JoinFiles(request);
                    Directory.Delete(uploadFolder, true);
                }



            }

            
            

        }
        catch (Exception ex)
        {
            StreamWriter writer = new StreamWriter(@"C:\upload\temp\message.txt");
            writer.WriteLine(ex);
            
            writer.Close();
            
        }
    }
    #endregion

    #region DeleteFile

    public int DeleteFile(string username, string pwd, string filepath)
    {
        //string fileDir = Path.Combine(@"C:\strorage", filepath);
        string fileDir =  filepath;
        if (File.Exists(fileDir))
        {
            try
            {
                File.Delete(fileDir);
                
            }
            
            catch (Exception ex)
            {
                StreamWriter writer = new StreamWriter(@"C:\storage\Admin_Errors\message.txt");
                writer.WriteLine(ex);
                writer.Close();
            }
            
        }
        return dao.DeleteFile(username, pwd, filepath);


    }


    #endregion


    #region GetList
    public List<FileInformation> GetList(string username, string pwd, int gID)
    {
            return dao.GetList(username, pwd, gID).ToList();
    }
    #endregion


    #region GetGroups
    public List<HelperClass> GetGroups()
    {

        return dao.getGroups();
    }
    #endregion

    #region AddUser
    public int AddUser(HelperClass user, HelperClass newUser)
    {
        
        return dao.addUser(user, newUser);

    }
    #endregion

    #region DeleteUser
    public int DeleteUser(string username, string pwd, string delUserName)
    {
        return dao.DeleteUser(username, pwd, delUserName);

    }

    #endregion

    #region AddGroup
    public int AddGroup(string username, string pwd, string groupName)
    {
        return dao.AddGroup(username, pwd, groupName);
        
    }

    #endregion

    #region DeleteGroup
    public int DelGroup(string username, string pwd, string groupName)
    {
        return dao.DelGroup(username, pwd, groupName);
    }

    #endregion

    #region ChangePassword
    public int ChangePassword(string username, string pwd, string updateUser, string newPwd)
    {
        return dao.ChangePassword(username, pwd, updateUser, newPwd);
        
    }

    #endregion

    #region GetUsers
    public List<HelperClass> GetUsers(string username, string pwd, string groupName)
    {
        return dao.GetUsers(username, pwd, groupName);
    }


    #endregion


    #region Decompress

    public void DecompressFiles(RemoteFileInfo fileInfo)
    {
        //SevenZipExtractor.SetLibraryPath(@"C:\Users\John\Desktop\SeniorCapstone 2\FileTrans\WCFFileTrans\Bin\7z.dll");
        SevenZipExtractor.SetLibraryPath(@"C:\inetpub\wwwroot\webservice\bin\7z.dll");

        HelperClass hc = new HelperClass();

        hc.UserName = fileInfo.UserName;
        hc.PassHash = fileInfo.Password;
        hc.UserGroup = fileInfo.Group;
            //dao.getUsersGroup(fileInfo.UserName, fileInfo.Password);
        
        
        //DirectoryInfo diSource = new DirectoryInfo(Path.GetDirectoryName(fileInfo.FileName)); //Get directory info to locate password file
        
        //string tempPath = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileInfo.FileName));
        
        //FileInfo[] fiPass = diSource.GetFiles(tempPath + ".password.7z"); //Locate password file and get information
        //FileInfo[] fiPass = diSource.GetFiles(tempPath + ".password.7z").ToArray();
        string[] fiPass = Directory.GetFiles(tempDir + "\\" + fileInfo.Group + "\\" + Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileInfo.FileName))), "*.password.7z");



        StreamWriter writer = new StreamWriter(@"C:\upload\temp\message2.txt");
        writer.WriteLine(fiPass[0] + " " + fileInfo.Password + " " + fileInfo.FileName);

        writer.Close();
        if (fiPass.Length == 1) //If it find password file return password
        {
            using (FileStream inStream = File.OpenRead(fiPass[0])) //Open file to be sent to extractor
            {
                SevenZipExtractor zipExtractor = new SevenZipExtractor(inStream, fileInfo.Password); //Pass stream and password for extraction
                zipExtractor.ExtractArchive(Path.GetDirectoryName(fileInfo.FileName)); //Extract file to given location
            }
            string encPath = Path.GetDirectoryName(fiPass[0]) + "\\" + Path.GetFileNameWithoutExtension(fiPass[0]);
            StreamReader sr = new StreamReader(encPath); //Create reader to read file
            string password = sr.ReadLine().ToString(); //Pass the password in the file to string to be sent back and used
            sr.Close(); //Close streamreader
            File.Delete(encPath); //Delete decrypted file so password can't be seen
            fileInfo.Password = password;
            
        }

        



        if (!fileInfo.FileName.Contains("password")) //Check if password file is missing or corrupt
        {
            using (FileStream inStream = File.OpenRead(fileInfo.FileName)) //Open file to be sent to extractor
            {
                SevenZipExtractor zipExtractor = new SevenZipExtractor(inStream, fileInfo.Password); //Pass stream and password for extraction
                zipExtractor.ExtractArchive(Path.GetDirectoryName(fileInfo.FileName)); //Extract file to given location
            }

            File.Delete(fileInfo.FileName); //Delete old compressed file
        }


        
    }


    #endregion

    #region JoinFiles: Decompresses and joins files already split and compressed.
    public void JoinFiles(RemoteFileInfo fileInfo)
    {
        //string extrPartsLoc = @"C:\storage\" + request.Group + "\\";
        //string extrDir = @"C:\storage\" + fileInfo.Group + "\\";
        this.fileLocation = fileInfo.FileName;
        storageDir = Path.Combine(storageDir, fileInfo.Group);

        try //Basic error checking
        {
            DirectoryInfo diSource = new DirectoryInfo(Path.GetDirectoryName(fileLocation)); //Get Directory information

            if (File.Exists(Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation))))) //Check if file already exists
            {
                File.Delete(Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation)))); //Remove file if already atempted once
            }
            FileStream outStream = new FileStream(Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation))), FileMode.Append); //Create stream to join files in
            diSource = new DirectoryInfo(Path.GetDirectoryName(fileLocation)); //Update directory info
            foreach (FileInfo fiPart in diSource.GetFiles(@"*.part*")) //Join all files that end in .part*
            {
                Byte[] bytePart = File.ReadAllBytes(fiPart.FullName); //Read file to byte array
                outStream.Write(bytePart, 0, bytePart.Length); //Add byte array to already created file
            }
            outStream.Close(); //Close stream
            //Directory.Delete(Path.GetDirectoryName(fileLocation), true); //Delete directory with temp files
            //fileInfo.FileSize = Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation))).Length;
           // dao.AddFile(fileInfo.UserName, fileInfo.Password, Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation))), fileInfo.Group, fileInfo.FileSize);
            FileInfo fiTemp = new FileInfo(Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation))));
            dao.AddFile(fileInfo.UserName, fileInfo.Password, Path.Combine(storageDir, Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileLocation))), fileInfo.Group, fiTemp.Length);
        
        
        
        }
        catch (Exception ex)
        {
            StreamWriter writer = new StreamWriter(@"C:\upload\temp\ExceptionmessageJoinFiles.txt");
            writer.WriteLine(ex);

            writer.Close();
        }
    }
    #endregion

    #region BeginSplit files: Start worker thread for splitting and compressing of files
    public void BeginSplitFiles(string fileLocation, HelperClass user)
    {
        try //basic error handleing
        {
            if (File.Exists(fileLocation)) //Check to make sure file exists and has permissions to read
            {
                SplitJoinCompress fsj = new SplitJoinCompress(fileLocation, user); //Pass fileLocation and password to be used in thread
                Thread sjc = new Thread(new ThreadStart(fsj.SplitFiles));
                sjc.Name = Path.GetFileName(fileLocation);
                sjc.IsBackground = true;
                //active.threadStore.Add(sjc);
                sjc.Start(); //Start thread
            }
            else
            {
                //Post error for troubleshooting
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\message.txt");
                writer.WriteLine("***Error*** Either you don't have permissions to access this file, it is in use by another program, or the file no longer exists");
                writer.Close();
            
            }
        }
        catch (Exception ex)
        {
            StreamWriter writer = new StreamWriter(@"C:\upload\temp\ExceptionError.txt");
            writer.WriteLine("***ERROR*** in BeginSplitFiles: " + ex.Message);
            writer.Close();
            
        }
    }
    #endregion

    public class SplitJoinCompress
    {
        private string fileLocation; //Store location of file for thread
        private int fileParts = 52428800; //Size to split the files into, Setting lower can lead to instability, Default: 52428800
        private string password; //Stores password for encryption
        //frmMain active;
        HelperClass user;
        string activeDir = tempDir + "\\hct\\"; //Set main directory to store temp files
        //private string groupName;
        //private int status;

        public SplitJoinCompress(string fileLocation, HelperClass user)
        {
            this.fileLocation = fileLocation;
            //this.active = active;
            this.user = user;
            //this.groupName = groupName;
            //this.status = status;
        }

        #region SplitFiles: Splits files into deteremended size and compresses as each one finishes.
        public void SplitFiles()
        {
            SevenZipExtractor.SetLibraryPath(@"C:\Users\John\Desktop\SeniorCapstone 2\FileTrans\WCFFileTrans\Bin\7z.dll");
            try //Basic error checking
            {
                //int threadStatus = threadActivity.Count - 1;
                long fileOffset = 0; //Store starting posistion of each read
                string currPartPath; //Store full file path after broken into parts
                long totalFileSize; //Set file size to long to hold upto 9223372036854775807 bytes for large files
                int i = 0; //Used to define what part to save the chunck as

                //Specify folder name off of file
                string newPath = activeDir + "\\" + user.UserName + "\\" + Path.GetFileNameWithoutExtension(fileLocation);

                //Get file information to split accuratly
                FileInfo fiSource = new FileInfo(fileLocation);

                totalFileSize = (long)fiSource.Length; //Set total size of file

                //Check to see if exists, if it exists check files and finish split
                if (!Directory.Exists(newPath))
                {
                    this.password = RandomPasswordGenerator(); //Get random password to use on entire file
                    if (this.password == null)
                    {
                        throw new System.ArgumentException("Unable to create password");
                    }
                    Directory.CreateDirectory(newPath); //Create directory
                    ArchiveInformation(password, newPath, fiSource);

                }
                else //Check existing files and continue at last file attempted
                {
                    currPartPath = newPath + @"\" + fiSource.Name + ".password"; //set currPartPath to be used for encFile
                    this.password = RetrievePassword(currPartPath); //gets password of last session
                    DirectoryInfo diSource = new DirectoryInfo(Path.GetDirectoryName(currPartPath)); //get directory info to compair last session and start where left off
                    FileInfo[] fiPart = diSource.GetFiles(@"*.part****.7z");
                    if (fiPart.Length > 0)
                    {
                        i = fiPart.Length - 1; //i need to equal the last created file
                    }
                    File.Delete(fiPart[i].FullName); //Delete last file made and start from there
                    fileOffset = i * SplitFileSize(totalFileSize); //Correct offset for difference in files made
                    totalFileSize -= i * SplitFileSize(totalFileSize); //Shrinks totalFileSize to make up for the chunk that has already been read
                    
                }
                
                //Read file in chuncks
                using (BinaryReader b = new BinaryReader(File.Open(fileLocation, FileMode.Open)))
                {
                    while (totalFileSize != 0) //Loop through entire file until everything is read
                    {
                       // threadActivity[threadStatus].WaitOne(Timeout.Infinite);
                        
                        Byte[] byteSourceFile = new Byte[SplitFileSize(totalFileSize)]; //Create byte array to size of defined sizeRemaining
                        b.BaseStream.Seek(fileOffset, SeekOrigin.Begin); //Set binaryreader to start posistion of offset

                        //Set byte array to area that is needed to be split by the reader
                        byteSourceFile = b.ReadBytes((int)SplitFileSize(totalFileSize));

                        //Create new path for file that makes sure the files stay in order
                        currPartPath = newPath + @"\" + fiSource.Name + ".part" + i.ToString("0000");

                        //Read byte array into memory
                        MemoryStream fsNew = new MemoryStream(byteSourceFile);
                        fileOffset += SplitFileSize(totalFileSize); //Adjust fileOffset for next pass through
                        totalFileSize -= SplitFileSize(totalFileSize); //Shrinks totalFileSize to make up for the chunk that has already been read

                        

                        //Set properties to pass over for compression
                        Compress comFile = new Compress(); //Start new instance of compression properties
                        comFile.Location = currPartPath; //Set current file that was just split
                        comFile.Password = password; //Set password to be used in compression
                        comFile.FileName = Path.GetFileName(currPartPath); //Set just the file name
                        SevenZipCompressor szc = new SevenZipCompressor(); //Start new instance of compression settings
                        szc = comFile.SetProperties(comFile); //Set properties and return configured settings
                       
                        comFile.StartCompression(szc, comFile, fsNew); //Compress files in compress.cs
                        File.Copy(currPartPath, currPartPath + ".7z");
                        File.Delete(currPartPath);
                        
                        //FileSendRecieve fsr = new FileSendRecieve();
                        //fsr.StartTransfer(currPartPath + ".7z", i, user);
                        i++; //Iterate i for next file name
                    }
                }
            }

            catch (ThreadAbortException)
            {
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\ThreadAbortException.txt");
                writer.WriteLine("Stopped Transfering " + Path.GetFileName(fileLocation) + " and deleted temporary files.");
                writer.Close();

            }
            catch (Exception ex)
            {
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\ExceptionErrorSplitFiles.txt");
                writer.WriteLine("***ERROR*** " + ex.Message);
                writer.Close();

            }
        }
        #endregion

        #region SplitFileSize: Returns the amount to make each file seperation.
        private long SplitFileSize(long sizeRemaining)
        {
            if (sizeRemaining < (long)fileParts) //If left over filesize is larger, needs to return the ammount of bytes left to read
            {
                return sizeRemaining;
            }
            else
            {
                return fileParts;
            }
        }
        #endregion

        #region RandomPasswordGenerator: Creates a random 64byte string used for encrypting files
        private string RandomPasswordGenerator()
        {
            try
            {
                Random random = new Random((int)DateTime.Now.Ticks); //Set random based off clock
                StringBuilder builder = new StringBuilder();

                //Create 64byte string for password used
                char ch;
                for (int i = 0; i < 64; i++)
                {
                    ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); //Get random letter for password
                    builder.Append(ch); //Store in string builder
                }

                return builder.ToString(); //Return password
            }
            catch (Exception ex)
            {
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\ExceptionErrorRandomPasswordGenerator.txt");
                writer.WriteLine("***ERROR*** " + ex.Message);
                writer.Close();
                return null;
            }
        }
        #endregion

        #region ArchiveInformation: Creates password file to use for decryption on server/client side
        private void ArchiveInformation(string password, string newPath, FileInfo fiSource)
        {
            SevenZipExtractor.SetLibraryPath(@"C:\Users\John\Desktop\SeniorCapstone 2\FileTrans\WCFFileTrans\Bin\7z.dll");
            try //Basic error checking
            {
                MemoryStream encryptionPasswordFile = new MemoryStream(); //MemoryStream to hold file so it never touches disk until encrypted
                StreamWriter sw = new StreamWriter(encryptionPasswordFile); //Use StreamWriter to create file in memory
                sw.Write(password); //Write password to writer
                sw.Flush(); //Save changes to streamwritere
                Compress encFile = new Compress(); //New instance of properties to inc the file
                String currPartPath = newPath + @"\" + fiSource.Name + ".password"; //set currPartPath to be used for encFile
                encFile.Location = currPartPath; //Set location
                encFile.Password = user.PassHash; //Test password....Will get users password
                encFile.FileName = Path.GetFileName(currPartPath); //Set filename
                SevenZipCompressor ezc = encFile.SetProperties(encFile); //New instance of 7zcompressor
                encFile.StartCompression(ezc, encFile, encryptionPasswordFile); //Create encrypted file and clear memorystream
                File.Copy(currPartPath, currPartPath + ".7z");
                File.Delete(currPartPath);

                //FileSendRecieve fsr = new FileSendRecieve();
                //fsr.StartTransfer(currPartPath + ".7z", 0, user);
            }
            catch (Exception ex)
            {
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\ExceptionErrorArchiveInformation.txt");
                writer.WriteLine("***ERROR*** " + ex.Message);
                writer.Close();
            }
        }
        #endregion

        #region RetrievePassword: Method used to retrieve password
        private string RetrievePassword(string fileLocation)
        {
            try //Basic error checking
            {
                DirectoryInfo diSource = new DirectoryInfo(Path.GetDirectoryName(fileLocation)); //Get directory info to locate password file
                FileInfo[] fiPass = diSource.GetFiles(@"*.password.7z"); //Locate password file and get information

                if (fiPass.Length == 1) //If it find password file return password
                {
                    Compress encFile = new Compress(); //New instance of compress to set properties
                    encFile.Password = user.PassHash; //Set password to access password file
                    encFile.Location = fiPass[0].FullName; //Set the location of password file
                    encFile.StartDecompression(encFile, Path.GetDirectoryName(fileLocation)); //Decrypt file to extract password
                    string encPath = Path.GetDirectoryName(fileLocation) + @"\" + Path.GetFileNameWithoutExtension(fiPass[0].FullName); //Set path for decrypted password file
                    StreamReader sr = new StreamReader(encPath); //Create reader to read file
                    string password = sr.ReadLine().ToString(); //Pass the password in the file to string to be sent back and used
                    sr.Close(); //Close streamreader
                    File.Delete(encPath); //Delete decrypted file so password can't be seen
                    return password; //Return password to use for other files
                }
                else
                {
                    return null; //Password file was not found or is currupted so it returns null
                }
            }
            catch (Exception ex)
            {
                StreamWriter writer = new StreamWriter(@"C:\upload\temp\ExceptionErrorRetrievePassword.txt");
                writer.WriteLine("***ERROR*** " + ex.Message);
                writer.Close();
                return null;
            }
        }
        #endregion
    }
}
